
loessplot <- function(dataset,fill,title,outliertrim,limu=100,liml=0){
  data <- read.dta(dataset)
  if (title == "Denmark"){ 
    data <- subset(data,data$year == 2005)
    # mergers
  } else { 
    data <- subset(data,data$year == 2008)
  }
  data <- subset(data,data$pop > 500)
  data <- subset(data, data$pctforeign < quantile(data$pctforeign, c(outliertrim),na.rm=T))
  mdata <- (na.omit(data.frame(data$pctforeign,data$pctsocial)))
  x <- mdata$data.pctforeign*100
  y <- mdata$data.pctsocial*100
  lo <- loess(y~x)
  plot(x,y,pch=20,col="gray",xlab="% Foreign",ylab="% of Budget",main=title,type="n",ylim=c(liml,limu))
  if (fill ==1){ abline(v=0,col="gray98",lwd=800) }
  xl <- seq(min(x),max(x), (max(x) - min(x))/1000)
  pred.c <- predict(lo,xl,se=T)
  lines(xl, pred.c$fit, col='black', lwd=1)
  rug(x,col="black")
  min <- pred.c$fit -  pred.c$s*1.96
  max <- pred.c$fit +  pred.c$s*1.96
  polygon(c(xl,rev(xl)),c(max,rev(min)),col=adjustcolor("gray",alpha.f=0.4),border="white")
  box()	
}


general_loess <- function(x,y,span,xlab,ylab,ylim,title,xcut1=0,xcut2=1,trans=0,addplot=0){
  lo <- loess(y~x,span=span)
  if (xcut1==0 & xcut2==1 & addplot==0){
    xl <- seq(min(x),max(x), (max(x) - min(x))/1000)
    min <- min(x)
    max <- max(x)
  } else {
    min  <- quantile(x,xcut1,na.rm=T)
    if (addplot == 0){
      max <- quantile(x,xcut2,na.rm=T)
    } else {
      max <- addplot
    }
    xl <- seq(min,max, (max - min)/1000)
    oldmax <<- max
  }
  if (addplot==0){
    plot(x,y,pch=20,col="gray",xlab=xlab,ylab=ylab,ylim=ylim,main=title,type="n",cex.lab=.75,cex.axis=.7,xlim=c(min,max))
    grid()
    rug(x,col="black")
  }
  pred.c <- predict(lo,xl,se=T)
  min <- pred.c$fit -  pred.c$s*1.9
  max <- pred.c$fit +  pred.c$s*1.9
  
  if (trans==1){
    lty=2 
  }  else {
    lty=1
    polygon(c(xl,rev(xl)),c(max,rev(min)),col=adjustcolor("gray",alpha.f=0.3),border=NA)
  }
  lines(xl, pred.c$fit, col='black', lwd=1,lty=lty)
  box()
}
